package com.example.recall_application.utils;


import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;
import android.provider.Contacts;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Contacts.Data;
import android.provider.ContactsContract.RawContacts;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;


/**
 * @author Created by Insist_L on 2017/9/14.
 *         TODO: 对手机通讯录进行增删改查操作
 */

public class ContactsUtils {

    /**
     * 添加联系人
     *
     * @param context
     * @param name
     * @param phoneNumber
     */
    public static void insert(Context context, String name, String phoneNumber) {
        // 创建一个空的ContentValues
        ContentValues values = new ContentValues();

        // 向RawContacts.CONTENT_URI空值插入，
        // 先获取Android系统返回的rawContactId
        // 后面要基于此id插入值
        Uri rawContactUri = context.getContentResolver().insert(RawContacts.CONTENT_URI, values);
        long rawContactId = ContentUris.parseId(rawContactUri);


        if (!TextUtils.isEmpty(name)) {
            values.clear();
            values.put(Data.RAW_CONTACT_ID, rawContactId);
            // 内容类型
            values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
            // 联系人名字
            values.put(StructuredName.GIVEN_NAME, name);
            // 向联系人URI添加联系人名字
            context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
            values.clear();
        }


        if (!TextUtils.isEmpty(phoneNumber)) {
            values.clear();
            values.put(Data.RAW_CONTACT_ID, rawContactId);
            values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
            // 联系人的电话号码
            values.put(Phone.NUMBER, phoneNumber);
            // 电话类型
            values.put(Phone.TYPE, Phone.TYPE_MOBILE);
            // 向联系人电话号码URI添加电话号码
            context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
        }

//        values.clear();
//
//        values.put(Data.RAW_CONTACT_ID, rawContactId);
//        values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
//        // 联系人的Email地址
//        values.put(Email.DATA, "zhangphil@xxx.com");
//        // 电子邮件的类型
//        values.put(Email.TYPE, Email.TYPE_WORK);
//        // 向联系人Email URI添加Email数据
//        getContentResolver().insert(Data.CONTENT_URI, values);
    }

    /**
     * 删除联系人
     *
     * @param context
     * @param phoneNumber
     */
    public static void delete(Context context, String phoneNumber) {
        String contactId = getContactId(context, phoneNumber);
        if (TextUtils.isEmpty(contactId)) return;

        long rawContactId = Long.parseLong(contactId);
        context.getContentResolver().delete(ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), null, null);
    }

    /**
     * 修改联系人手机号
     *
     * @param rawRawContactId
     * @param newNumber
     */
    public static void update(Context context, String rawRawContactId, String newNumber) {
        ContentValues values = new ContentValues();
        values.put(CallLog.Calls.NUMBER, "1101141221");
//        values.put(CallLog.Calls.DATE, System.currentTimeMillis() );
//        values.put(CallLog.Calls.DURATION, 90);
//        values.put(CallLog.Calls.TYPE, 1);
//        values.put(CallLog.Calls.NEW, 0);

        ContentResolver resolver = context.getContentResolver();
      //  String Where = "number='15201962331'";
        Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, new String[] { "_id" }, "number=?",
                new String[] { "15201962331" },
                "_id desc limit 1");


        if (cursor.moveToFirst()) {
            int id = cursor.getInt(0);
            resolver.update(CallLog.Calls.CONTENT_URI,values, "_id=?", new String[] { id + "" });
            try{
                resolver.notifyChange(CallLog.Calls.CONTENT_URI,null);
            }catch (Exception e){
                e.toString();
            }

        }

//        if(!TextUtils.isEmpty(rawRawContactId)){
//           int result =  context.getContentResolver().update(CallLog.Calls.CONTENT_URI, values, Where, null);
//           try{
//               context.getContentResolver().notifyAll();
//           }catch (Exception e){
//               e.toString();
//           }
//
//            Toast.makeText(context, ""+result, Toast.LENGTH_SHORT).show();
//        }

    }

    public static void insertCallLog(String number, Context context, int duration, int type, int new_) {
        ContentValues values = new ContentValues();
        values.put(CallLog.Calls.NUMBER, number);
        values.put(CallLog.Calls.DATE, System.currentTimeMillis());
        values.put(CallLog.Calls.DURATION, duration);
        values.put(CallLog.Calls.TYPE, type);
        values.put(CallLog.Calls.NEW, new_);
        context.getContentResolver().insert(CallLog.Calls.CONTENT_URI, values);
    }

    /**
     * 删除某联系人最近的一次来电
     *
     * @param callLog
     */
    public static void deletLastCallLog(String insertLog,String callLog,Context context) {
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, new String[] { "_id" ,CallLog.Calls.DATE,CallLog.Calls.DURATION,CallLog.Calls.TYPE,CallLog.Calls.NEW}, "number=?", new String[] { callLog },
                "_id desc limit 1");
        if (cursor.moveToFirst()) {
            int id = cursor.getInt(0);

            int dura = cursor.getColumnIndex(CallLog.Calls.DURATION);
            int duras = cursor.getInt(dura);

            int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
            int types = cursor.getInt(type);

            int new_ = cursor.getColumnIndex(CallLog.Calls.NEW);
            int new_s = cursor.getInt(new_);

            resolver.delete(CallLog.Calls.CONTENT_URI, "_id=?", new String[] { id + "" });
            insertCallLog(insertLog,context
            ,duras
            ,types
            ,new_s);
        }
    }



    /**
     * 根据手机号查询通讯录中对应的ContactId
     * @param context
     * @param number
     * @return 通讯录中对应的ContactId
     */
    public static String getContactId(Context context, String number) {
        Cursor c = null;
        try {
            c = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
                    new String[]{CallLog.Calls.NUMBER}, null, null, null);
            if (c != null && c.moveToFirst()) {
                    String phone = c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));
                    if(number.equals(phone)){
                        return c.getColumnIndex(CallLog.Calls.CACHED_PHOTO_ID)+"";
                    }
                    c.moveToNext();
            }
        } catch (Exception e) {
            Log.e("tag", "getContactId error:", e);
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return null;
    }



}
